package com.zhdl.hardware_contact.hardware_web.service;

import cn.hutool.core.lang.Opt;
import cn.hutool.core.util.HexUtil;
import com.project.common.bean.BaseQueryCriteria;
import com.project.network.entity.PortComm;
import com.project.network.entity.PortSocket;

import com.zhdl.common.ytools.springContext.CommonParmaOpt;
import com.zhdl.common.ytools.springContext.SpringContextHolder;
import com.zhdl.hardware_contact.hardware_config.entity.ProjectConfiguration;
import com.zhdl.hardware_contact.hardware_config.entity.ProjectParameter;
import com.zhdl.hardware_contact.hardware_config.service.ProjectConfigService;
import com.zhdl.hardware_contact.hardware_config.service.ProjectParamService;
import com.zhdl.hardware_contact.hardware_config.service.dto.ProjectConfigQueryCriteria;
import com.zhdl.hardware_contact.hardware_config.service.dto.ProjectParamQueryCriteria;
import com.zhdl.hardware_contact.hardware_param.entity.*;
import com.zhdl.hardware_contact.hardware_param.service.*;
import com.zhdl.hardware_contact.hardware_param.service.dto.HardwareActionDictQueryCriteria;
import com.zhdl.hardware_contact.hardware_param.service.dto.HardwareActionMiddleQueryCriteria;
import com.zhdl.hardware_contact.hardware_param.service.dto.ProjectActionDictQueryCriteria;
import com.zhdl.hardware_contact.hardware_param.service.impl.HardwareAbsPosServiceImpl;
import com.zhdl.hardware_contact.hardware_web.request.*;
import com.zhdl.hardware_contact.hardware_web.respone.*;
import com.zhdl.modules.common.production.service.ProductionService;
import com.zhdl.modules.common.protocol_param.service.ProtocolParamService;

import com.zhdl.modules.process.service.ProjectConfigProcessService;
import lombok.Value;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.lang.module.Configuration;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class HardwareContactService {

    @Resource
    SpringContextHolder springContextHolder;
    @Resource
    private ProjectConfigService projectConfigService;

    @Resource
    private ProjectParamService projectParamService;
    @Resource
    private HardwareDictionaryService hardwareDictionaryService;
    @Resource
    private HardwareTypeDictService hardwareTypeDictService;
    @Resource
    private HardwareActionDictService hardwareActionDictService;
    @Resource
    private HardwareActionMiddleService hardwareActionMiddleService;
    @Resource
    private HardwareActionParamDictService hardwareActionParamDictService;
    @Resource
    private ProjectActionDictService projectActionDictService;
    @Resource
    private ProtocolParamService protocolParamService;


    @Resource
    private HardwareWorkplaceService hardwareWorkplaceService;

    @Resource
    private HardwareCurrentService hardwareCurrentService;

    @Resource
    private HardwareAbsPosServiceImpl hardwareAbsPosServiceImpl;



    /* 通过字段名 获取要使用的Service */
    public void controlHardwareSendByProtocol(ProjectConfiguration projectConfiguration, String protocolName, String port) {
        springContextHolder.getOpt(protocolName).paramOpt(projectConfiguration, port);
    }

    /*---------------------------------------- 项目配置 ----------------------------------------*/

    /**
     * 保存项目配置 -- 手动添加的项目配置 用于删除修改
     *
     * @param projectConfiguration 项目配置
     * @return /
     */
    public ProjectConfiguration saveProjectConfig(ProjectConfiguration projectConfiguration) {
        return projectConfigService.insert(projectConfiguration);
    }

    /**
     * 更新项目配置 -- 手动添加的项目配置 用于删除修改
     *
     * @param projectConfiguration 项目配置
     * @return /
     */
    public ProjectConfiguration updateProjectConfig(ProjectConfiguration projectConfiguration) {
        return projectConfigService.update(projectConfiguration, projectConfiguration.getId());
    }

    /**
     * 项目配置-删除
     */
    public void deleteProjectConfig(Integer id) {
        projectConfigService.deleteById(id);
    }

    /**
     * 项目配置-查询
     *
     * @return /
     */
    public List<ProjectConfiguration> getProjectConfig() {
        return projectConfigService.selectAll();
    }

    /**
     * 项目配置-查询 通过Id
     *
     * @return /
     */
    public ProjectConfiguration getProjectConfigById(Integer id) {
        return projectConfigService.selectById(id);
    }

    /**
     * 项目配置，查询
     *
     * @param queryCriteria 查询条件
     * @return /
     */
    public List<ProjectConfiguration> getProjectConfigByCondition(ProjectConfigQueryCriteria queryCriteria) {
        return projectConfigService.findList(queryCriteria);
    }

    /*---------------------------------------- 项目参数 ----------------------------------------*/

    /**
     * 项目配置，查询
     *
     * @param queryCriteria 查询条件
     * @param pageable      分页条件
     * @return /
     */
    public Page<ProjectConfigurationResp> getProjectConfigByCondition(ProjectConfigQueryCriteria queryCriteria, Pageable pageable) {
        List<HardwareWorkplace> workplaces = getworkplaceTypeDict();
        Map<Integer,String> workplaceMap = new HashMap<>();
        for (HardwareWorkplace workplace : workplaces) {
            workplaceMap.put(workplace.getId(),workplace.getWorkplaceName());
        }

        Page<ProjectConfiguration> projectConfigurations = projectConfigService.findAllPage(queryCriteria, pageable);
        List<ProjectConfigurationResp> dtoList = projectConfigurations.getContent().stream()
                .map(pc -> ProjectConfigurationResp.fromProjectConfiguration(pc, workplaceMap.get(pc.workplaceId)))
                .collect(Collectors.toList());

        Page<ProjectConfigurationResp> respPage = new PageImpl<>(dtoList, projectConfigurations.getPageable(), projectConfigurations.getTotalElements());


        return respPage;
    }

    /**
     * 保存项目参数 -- 手动添加的项目参数设置 用于删除修改
     *
     * @param projectParameter 项目参数
     * @return /
     */
    public ProjectParameter saveProjectParam(ProjectParameter projectParameter) {
        return projectParamService.insert(projectParameter);
    }

    /**
     * 更新项目参数 -- 手动添加的项目参数设置 用于删除修改
     *
     * @param projectParameter 项目参数
     * @return /
     */
    public ProjectParameter updateProjectParam(ProjectParameter projectParameter) {
        return projectParamService.update(projectParameter, projectParameter.getId());
    }

    /**
     * 项目参数-删除
     */
    public void deleteProjectParam(Integer id) {
        projectParamService.deleteById(id);
    }

    /**
     * 项目参数-查询 通过Id
     *
     * @return /
     */
    public ProjectParameter getProjectParamById(Integer id) {
        return projectParamService.selectById(id);
    }

    /**
     * 项目参数-查询
     *
     * @return /
     */
    public List<ProjectParameter> getProjectParam() {
        return projectParamService.selectAll();
    }

    /**
     * 项目参数，查询
     *
     * @param queryCriteria 查询条件
     * @return /
     */
    public List<ProjectParameter> getProjectParamByCondition(ProjectParamQueryCriteria queryCriteria) {
        return projectParamService.findList(queryCriteria);
    }

    /**
     * 项目参数，查询
     *
     * @param queryCriteria 查询条件
     * @param pageable      分页条件
     * @return /
     */
    public Page<ProjectParameter> getProjectParamByCondition(ProjectParamQueryCriteria queryCriteria, Pageable pageable) {
        return projectParamService.findAllPage(queryCriteria, pageable);
    }

    /*---------------------------------------- 项目硬件类型 ----------------------------------------*/

    public List<ProjectActionDict> getProjectActionByCondition(ProjectActionDictQueryCriteria queryCriteria) {
        return projectActionDictService.findList(queryCriteria);
    }

    /**
     * 项目硬件类型-新增
     *
     * @param hardwareTypeDict 项目硬件信息
     * @return /
     */
    public HardwareTypeDict saveHardwareTypeDict(HardwareTypeDict hardwareTypeDict) {
        return hardwareTypeDictService.insert(hardwareTypeDict);
    }


    /**
     * 项目硬件工位类型-新增
     *
     * @param hardwareWorkplace
     * @return
     */
    public HardwareWorkplace saveHardwareWorkplace(HardwareWorkplace hardwareWorkplace) {
        return hardwareWorkplaceService.insert(hardwareWorkplace);
    }


    /**
     * 项目硬件工位-删除
     */
    public void deleteHardwareWorkplace(Integer id) {
        hardwareWorkplaceService.deleteById(id);
    }

    /**
     * 项目硬件类型-更新
     *
     * @param hardwareTypeDict 项目硬件信息
     * @return /
     */
    public HardwareTypeDict updateHardwareTypeDict(HardwareTypeDict hardwareTypeDict) {
        return hardwareTypeDictService.update(hardwareTypeDict, hardwareTypeDict.getId());
    }

    /**
     * 项目硬件类型-删除
     */
    public void deleteHardwareTypeDict(Integer id) {
        hardwareTypeDictService.deleteById(id);
    }

    /**
     * 项目硬件类型-查询
     *
     * @return /
     */
    public List<HardwareTypeDict> getHardwareTypeDict() {
        return hardwareTypeDictService.selectAll();
    }


    /**
     * 项目硬件工位-查询
     *
     * @return /
     */
    public List<HardwareWorkplace> getworkplaceTypeDict() {
        return hardwareWorkplaceService.selectAll();
    }

    /*---------------------------------------- 项目硬件动作 ----------------------------------------*/

    /**
     * 项目硬件类型-查询 通过Id
     *
     * @return /
     */
    public HardwareTypeDict getHardwareTypeDictById(Integer id) {
        return hardwareTypeDictService.selectById(id);
    }

    /**
     * 项目硬件动作-新增
     *
     * @param hardwareActionDict 项目硬件信息
     * @return /
     */
    public HardwareActionDict saveHardwareActionDict(HardwareActionDict hardwareActionDict) {
        return hardwareActionDictService.insert(hardwareActionDict);
    }

    /**
     * 项目硬件动作-更新
     *
     * @param hardwareActionDict 项目硬件信息
     * @return /
     */
    public HardwareActionDict updateHardwareActionDict(HardwareActionDict hardwareActionDict) {
        return hardwareActionDictService.update(hardwareActionDict, hardwareActionDict.getId());
    }

    /**
     * 项目硬件动作-删除
     */
    public void deleteHardwareActionDict(Integer id) {
        hardwareActionDictService.deleteById(id);
    }

    /**
     * 项目硬件动作-查询
     *
     * @return /
     */
    public List<HardwareActionDict> getHardwareActionDict() {
        return hardwareActionDictService.selectAll();
    }

    /**
     * 项目硬件参数，查询
     *
     * @param queryCriteria 查询条件
     * @return /
     */
    public List<HardwareActionDict> getHardwareActionDictByCondition(HardwareActionDictQueryCriteria queryCriteria) {
        return hardwareActionDictService.findList(queryCriteria);
    }

    /**
     * 项目硬件动作-查询 通过Id
     *
     * @return /
     */
    public HardwareActionDict getHardwareActionDictById(Integer id) {
        return hardwareActionDictService.selectById(id);
    }

    /*---------------------------------------- 项目详情🔎 ----------------------------------------*/

    /**
     * 控制运动-手动输入控制
     */
    public void controlHardwareRun(ControlCmdSetReq req) {
        //查询硬件详情
        HardwareInfoViewResp hardwareInfo = getHardwareInfo(req.getHardwareId());
        String portD;
        String hardwareProtocol = hardwareInfo.getHardware_protocol();

        //获取需要写入的端口号
        String type = hardwareInfo.getHardware_protocol_view().getType();
        if (type.equals("com")) {
            if (hardwareInfo.getHardware_protocol_view().getPortComm() != null) {
                portD = hardwareInfo.getHardware_protocol_view().getPortComm().getPort();
                log.info("写入的COMIP地址:{},,,{}", portD, hardwareProtocol);
            } else {
                portD = "";
            }
        } else {
            if (hardwareInfo.getHardware_protocol_view().getPortSocket() != null) {
                String clientIp = hardwareInfo.getHardware_protocol_view().getPortSocket().getServerIp();
                String clientPort = hardwareInfo.getHardware_protocol_view().getPortSocket().getServerPort();
                portD = clientIp + ":" + clientPort;
                log.info("写入的TCPIP地址:{},,,{}", portD, hardwareProtocol);
            } else {
                portD = "";
            }
        }

        //获取硬件下的所有动作
        hardwareInfo.getConfigActionList().forEach(configAction -> {
            //指定动作
            if (Objects.equals(configAction.getId(), req.getActionId())) {
                //获取动作下的参数
                List<HardwareInfoActionConfigResp> hardwareInfoActionConfigRespList =
                        configAction.getHardwareInfoActionConfigRespList();
                //如果参数相等，则设置

//                hardwareInfoActionConfigRespList.forEach(hardwareInfoActionConfigResp -> {
//                    req.getActionParam().forEach(controlCmdSetValueReq -> {
//                        if (Objects.equals(hardwareInfoActionConfigResp.getId(), controlCmdSetValueReq.getParamId())) {
//                            String address = hardwareInfoActionConfigResp.getProjectConfiguration().getAddress();
//                            String value = controlCmdSetValueReq.getParamValue();
//                            hardwareInfoActionConfigResp.getProjectConfiguration().setValue(value);
//
//                            controlHardwareSendByProtocol(hardwareInfoActionConfigResp.getProjectConfiguration(), hardwareProtocol, portD);
//                        }else{
//                            controlHardwareSendByProtocol(hardwareInfoActionConfigResp.getProjectConfiguration(), hardwareProtocol, portD);
//                        }
//                    });
//                });

                Float magnification = hardwareInfo.getMagnification();

                for (int i = 0; i < hardwareInfoActionConfigRespList.size(); i++) {
                    HardwareInfoActionConfigResp hardwareInfoActionConfigResp = hardwareInfoActionConfigRespList.get(i);
                    if(hardwareInfoActionConfigResp.getProjectConfiguration().getValueType()==3){
                        float v = Float.parseFloat(req.getActionParam().get(i).getParamValue()) * magnification;
                        req.getActionParam().get(i).setParamValue(String.valueOf(v));
                    }
                    hardwareInfoActionConfigResp.getProjectConfiguration().setValue(req.getActionParam().get(i).getParamValue());
                    log.info("{}",hardwareInfoActionConfigResp.getProjectConfiguration());

                    controlHardwareSendByProtocol(hardwareInfoActionConfigResp.getProjectConfiguration(), hardwareProtocol, portD);

                }

            }
        });
    }



    /**
     * 控制运动-参数列表控制
     */
    public void controlHardwareRun(Integer hardwareId, Integer paramId) {
        List<ProjectActionConfigResp> projectActionConfigRespList = new ArrayList<>();
        HardwareInfoViewResp hardwareInfo = getHardwareInfo(hardwareId);
        hardwareInfo.getConfigActionList().forEach(configAction -> {
            List<HardwareInfoActionConfigResp> hardwareInfoActionConfigRespList =
                    configAction.getHardwareInfoActionConfigRespList();
            hardwareInfoActionConfigRespList.forEach(actionConfig -> {
                if (actionConfig.getParamId().contains(String.valueOf(paramId))) {
                    projectActionConfigRespList.add(configAction);
                }
            });
        });
        if (!projectActionConfigRespList.isEmpty()) {
            String portD = "";

            ProjectActionConfigResp projectActionConfigResp = projectActionConfigRespList.get(0);
            List<HardwareInfoActionConfigResp> actionRunList = projectActionConfigResp.getHardwareInfoActionConfigRespList();
            String hardwareProtocol = hardwareInfo.getHardware_protocol();

            String type = hardwareInfo.getHardware_protocol_view().getType();
            if (type.equals("com")) {
                if (hardwareInfo.getHardware_protocol_view().getPortComm() != null) {
                    portD = hardwareInfo.getHardware_protocol_view().getPortComm().getPort();
                    log.info("写入的IP地址:{},,,{}", portD, hardwareProtocol);
                }
            } else {
                if (hardwareInfo.getHardware_protocol_view().getPortSocket() != null) {
                    String clientIp = hardwareInfo.getHardware_protocol_view().getPortSocket().getServerIp();
                    String clientPort = hardwareInfo.getHardware_protocol_view().getPortSocket().getServerPort();
                    portD = clientIp + ":" + clientPort;
                    log.info("写入的IP地址:{},,,{}", portD, hardwareProtocol);
                }
            }

            //所有的动作详情
            for (HardwareInfoActionConfigResp hardwareInfoActionConfigResp : actionRunList) {
                //判断是否配置有地址 如果无 则不运动
                if (hardwareInfoActionConfigResp.getProjectConfiguration() != null) {
                    //获取地址 以及要写入的值
                    ProjectConfiguration projectConfiguration = hardwareInfoActionConfigResp.getProjectConfiguration();
                    //获取动作下的所有参数列表
                    List<ProjectParameter> projectParameter = hardwareInfoActionConfigResp.getProjectParameter();
                    //查找有没有匹配的参数
                    List<ProjectParameter> nonNullProjectParameters = projectParameter.stream()
                            .filter(Objects::nonNull) // 过滤掉null元素
                            .toList();// 收集结果回到List（如果需要的话）

                    Optional<ProjectParameter> projectParameterResult = nonNullProjectParameters.stream()
                            .filter(projectParameterList -> projectParameterList.getId().equals(paramId))
                            .findFirst();

                    // 然后你可以通过 Optional 来安全地获取值
                    if (projectParameterResult.isPresent()) {
                        ProjectParameter result = projectParameterResult.get();
                        // 现在你可以使用 result 了
                        String address = projectConfiguration.getAddress();
                        {
                            //发送指令
                            String value = result.getValue();
                            log.info("写入的地址:{},写入的值:{}", address, value);
                            projectConfiguration.setValue(value);
                        }
                        controlHardwareSendByProtocol(projectConfiguration, hardwareProtocol, portD);
                    } else {
                        controlHardwareSendByProtocol(projectConfiguration, hardwareProtocol, portD);
                    }
                }
            }
        }
    }

    /**
     * 运行端 - 查询所有硬件详情
     *
     * @return /
     */
    public List<HardwareInfoViewResp> getHardwareInfoAll() {
        List<HardwareInfoViewResp> hardwareInfoViewRespList = new ArrayList<>();
        List<HardwareDictionary> hardwareDict = hardwareDictionaryService.selectAll();
        for (HardwareDictionary hardwareDictionary : hardwareDict) {
            HardwareInfoViewResp hardwareInfo = getHardwareInfo(hardwareDictionary.getId());
            hardwareInfoViewRespList.add(hardwareInfo);
        }
        return hardwareInfoViewRespList;
    }

    /**
     * 运行端 - 查询硬件 By workplaceId
     *
     * @param workplaceId
     * @return
     */
    public List<HardwareInfoViewResp> getHardwareInfoByworkplaceId(Integer workplaceId) {
        List<HardwareInfoViewResp> hardwareInfoViewRespList = new ArrayList<>();
        List<HardwareDictionary> hardwareDict = hardwareDictionaryService.HardwareInfoByworkplaceId(workplaceId);
        for (HardwareDictionary hardwareDictionary : hardwareDict) {
            HardwareInfoViewResp hardwareInfo = getHardwareInfo(hardwareDictionary.getId());
            Map<Integer ,List<ProjectConfiguration>> currentMap = new HashMap<>();
            List<ProjectConfiguration> temp = new ArrayList<>();
            for (ProjectConfiguration projectConfiguration : HardwareCurrentService.HardwareCurrentAddressMessageMap.get(hardwareDictionary.getId())) {

                temp.add(projectConfiguration);

            }
            currentMap.put(hardwareDictionary.getId() , temp);
            hardwareInfo.setHardwareCurrentMsg(currentMap);
            hardwareInfo.setDirection(hardwareDictionary.getDirection());

            //获取硬件下Abs信息
            List<HardwareAbsPosResp> hardwareAbsPosList = new ArrayList<>();
            for (HardwareAbsPos hardwareAbsPos : hardwareAbsPosServiceImpl.findByHardwareId(hardwareDictionary.getId())) {
                HardwareAbsPosResp hardwareAbsPosResp = new HardwareAbsPosResp();
                BeanUtils.copyProperties(hardwareAbsPos,hardwareAbsPosResp);
                hardwareAbsPosList.add(hardwareAbsPosResp);
            }
            hardwareInfo.setAbsPosList(hardwareAbsPosList);

            //获取气缸开关参数
            List<HardwareConfigResp> paramConfigList = new ArrayList<>();
            if(hardwareInfo.getHardware_type().equals("气缸_双线圈")){
                for (ProjectActionConfigResp projectActionConfigResp : hardwareInfo.getConfigActionList()) {
                    for (HardwareInfoActionConfigResp hardwareInfoActionConfigResp : projectActionConfigResp.getHardwareInfoActionConfigRespList()) {
                        HardwareConfigResp hardwareConfigResp = new HardwareConfigResp();
                        BeanUtils.copyProperties(hardwareInfoActionConfigResp.getProjectConfiguration(),hardwareConfigResp);

                        //获取内存中气缸开关参数value,用来确定开关状态
                        hardwareCurrentService.getProjectConfiguration(ProjectConfigProcessService.projectConfigurations,hardwareConfigResp);
                        paramConfigList.add(hardwareConfigResp);
                    }
                    //paramNameList.add(projectActionConfigResp.getHardwareInfoActionConfigRespList().get(0).getProjectConfiguration().getRemarks());
                }
            }



            if(hardwareInfo.getHardware_type().equals("电机")){
                for (ProjectActionConfigResp projectActionConfigResp : hardwareInfo.getConfigActionList()) {
                    if(projectActionConfigResp.getName().equals("run")) {
                        for (HardwareInfoActionConfigResp hardwareInfoActionConfigResp : projectActionConfigResp.getHardwareInfoActionConfigRespList()) {
                            HardwareConfigResp hardwareConfigResp = new HardwareConfigResp();
                            BeanUtils.copyProperties(hardwareInfoActionConfigResp.getProjectConfiguration(), hardwareConfigResp);

                            //获取内存中气缸开关参数value,用来确定开关状态
                            hardwareCurrentService.getProjectConfiguration(ProjectConfigProcessService.projectConfigurations, hardwareConfigResp);
                            paramConfigList.add(hardwareConfigResp);
                        }
                    }
                    //paramNameList.add(projectActionConfigResp.getHardwareInfoActionConfigRespList().get(0).getProjectConfiguration().getRemarks());
                }
            }

            hardwareInfo.setParamConfigList(paramConfigList);
            hardwareInfoViewRespList.add(hardwareInfo);




        }
        return hardwareInfoViewRespList;
    }


    /**
     * 运行端 - 查询IO By workpalceId
     * @param workplaceId
     * @return
     */

    public List<ProjectConfiguration> getConfigByworkplaceId(Integer workplaceId) {
        for (ProjectConfiguration projectConfiguration : projectConfigService.getProjectConfigurationByworkplaceId(workplaceId)) {
            projectConfiguration = hardwareCurrentService.getProjectConfiguration(ProjectConfigProcessService.projectConfigurations,projectConfiguration);
        }

        return projectConfigService.getProjectConfigurationByworkplaceId(workplaceId);
    }


    /**
     * 运行端 - 查询硬件详情
     *
     * @param id 硬件Id
     * @return /
     */
    public HardwareInfoViewResp getHardwareInfo(Integer id) {
        HardwareInfoViewResp hardwareInfoViewResp = new HardwareInfoViewResp();
        HardwareDictionary hardwareDictById = hardwareDictionaryService.selectById(id);
        if (hardwareDictById != null) {
            //设置硬件基本信息
            hardwareInfoViewResp.setMagnification(hardwareDictById.getMagnification());
            hardwareInfoViewResp.setRemarks(hardwareDictById.getRemarks());
            hardwareInfoViewResp.setHardware_id(id);
            hardwareInfoViewResp.setHardware_name(hardwareDictById.getName());
            hardwareInfoViewResp.setHardware_protocol(hardwareDictById.getProtocolName());
            hardwareInfoViewResp.setShow_array(hardwareDictById.getShowArray());
            HardwareProtocolViewResp hardware_protocol_view = new HardwareProtocolViewResp();
            //设置协议
            if (hardwareDictById.getProtocolType() != null) {
                if (hardwareDictById.getProtocolType().contains("com")) {
                    hardware_protocol_view.setType("com");
                    PortComm portCommById = protocolParamService.findPortCommById(String.valueOf(hardwareDictById.getProtocolTypeInfo()));
                    hardware_protocol_view.setPortComm(portCommById);
                } else {
                    hardware_protocol_view.setType("tcp");
                    PortSocket portSocketById = protocolParamService.findPortSocketById(String.valueOf(hardwareDictById.getProtocolTypeInfo()));
                    hardware_protocol_view.setPortSocket(portSocketById);
                }
                hardwareInfoViewResp.setHardware_protocol_view(hardware_protocol_view);
            }

            //设置硬件类型
            HardwareTypeDict hardwareTypeDictById = hardwareTypeDictService.selectById(hardwareDictById.getHardwareType());
            if (hardwareTypeDictById != null) {
                hardwareInfoViewResp.setHardware_type(hardwareTypeDictById.getName());
            }

            //设置参数列表
            List<ProjectParameter> projectParameters = new ArrayList<>();
            String paramArray = hardwareDictById.getParamArray();
            List<Integer> ids1 = stringArrayToIntegerArray(paramArray);
            if (!ids1.isEmpty()) {
                List<ProjectParameter> batchResult = projectParamService.findAllByIds(ids1);
                projectParameters.addAll(batchResult);
                hardwareInfoViewResp.setParamList(projectParameters);
            }

            //查询动作参数详情
            List<Integer> hardwareIds = insertList(hardwareDictById.getId());
            HardwareActionMiddleQueryCriteria queryCriteria = new HardwareActionMiddleQueryCriteria();
            queryCriteria.setHardwareId(hardwareIds);
            List<HardwareActionMiddle> actionMiddles = hardwareActionMiddleService.findList(queryCriteria);
            if (!actionMiddles.isEmpty()) {
                List<HardwareInfoActionConfigResp> actionParamResults = new ArrayList<>();
                actionMiddles.forEach(actionMiddle -> {
                    HardwareActionParamDict hardwareActionParamDict = hardwareActionParamDictService.selectById(actionMiddle.getParamId());
                    if (hardwareActionParamDict != null) {
                        HardwareInfoActionConfigResp actionParamResult = new HardwareInfoActionConfigResp();
                        BeanUtils.copyProperties(hardwareActionParamDict, actionParamResult);
                        HardwareActionDict hardwareActionDict = hardwareActionDictService.selectById(hardwareActionParamDict.getActionId());
                        if (hardwareActionDict != null) {
                            actionParamResult.setActionDict(hardwareActionDict);
                        }
                        ProjectConfiguration projectConfiguration = projectConfigService.selectById(hardwareActionParamDict.getAddressId());
                        if (projectConfiguration != null) {
                            actionParamResult.setProjectConfiguration(projectConfiguration);
                        }

                        List<ProjectParameter> ProjectParameterList = new ArrayList<>();
                        if (!Objects.equals(hardwareActionParamDict.getParamId(), "-999")) {
                            String[] paramId = hardwareActionParamDict.getParamId().split(",");
                            for (String s : paramId) {
                                ProjectParameter projectParameter = projectParamService.selectById(Integer.parseInt(s));
                                ProjectParameterList.add(projectParameter);
                            }
                        } else {
                            ProjectParameter projectParameter = projectParamService.selectById(Integer.parseInt(hardwareActionParamDict.getParamId()));
                            ProjectParameterList.add(projectParameter);
                        }
                        if (!ProjectParameterList.isEmpty()) {
                            actionParamResult.setProjectParameter(ProjectParameterList);
                        }
                        actionParamResults.add(actionParamResult);

                    }
                });

                List<ProjectActionConfigResp> actionResult = new ArrayList<>();
                ProjectActionDictQueryCriteria queryCriteria1 = new ProjectActionDictQueryCriteria();
                queryCriteria1.setHardwareId(hardwareIds); // 假设hardwareIds是一个已知且可用的集合
                List<ProjectActionDict> projectActionByCondition = getProjectActionByCondition(queryCriteria1);

                // 使用Java 8的Stream API来简化集合处理
                for (ProjectActionDict projectActionDict : projectActionByCondition) {
                    ProjectActionConfigResp projectActionConfigResp = new ProjectActionConfigResp();
                    BeanUtils.copyProperties(projectActionDict, projectActionConfigResp);
                    // 将paramIds字符串数组转换为整数列表
                    List<Integer> paramIds = stringArrayToIntegerArray(projectActionDict.getParamIds());
                    // 使用Stream API和filter来匹配actionParamResults
                    List<HardwareInfoActionConfigResp> matchedActionParams =
                            actionParamResults.
                                    stream().filter(
                                            actionParamResult -> paramIds.contains(actionParamResult.getId())).
                                    collect(Collectors.toList());
                    // 设置匹配的actionParams到response对象
                    projectActionConfigResp.setHardwareInfoActionConfigRespList(matchedActionParams);
                    // 将处理好的response对象添加到结果列表中
                    actionResult.add(projectActionConfigResp);
                }
                hardwareInfoViewResp.setConfigActionList(actionResult);
            }
        }
        return hardwareInfoViewResp;
    }

    /**
     * 配置端-保存硬件详情信息
     *
     * @param hardwareDictionary 硬件基本详情
     * @return /
     */
    public HardwareDictionary saveHardwareInfo(HardwareDictionary hardwareDictionary) {
        //保存硬件详情
        HardwareDictionary hardwareDictionaryResult = hardwareDictionaryService.insert(hardwareDictionary);

        // 查询硬件类型所拥有的动作
        HardwareTypeDict hardwareTypeDict = hardwareTypeDictService.selectById(hardwareDictionary.getHardwareType());
        if (hardwareTypeDict == null) {
            return new HardwareDictionary();
        }
        // 解析硬件类型所拥有的具体动作ID
        List<Integer> ids = Arrays.stream(hardwareTypeDict.getTypeActionArray().split(",")).map(Integer::parseInt).collect(Collectors.toList());
        // 查询硬件类型所拥有的具体动作信息，并使用Map提高查找效率
        Map<Integer, List<HardwareActionDict>> actionDictMap = backHardwareAction(ids).stream().collect(Collectors.groupingBy(HardwareActionDict::getId, Collectors.toList()));
        // 创建并保存动作参数和中间表记录
        for (Map.Entry<Integer, List<HardwareActionDict>> entry : actionDictMap.entrySet()) {
            Integer id = entry.getKey();
            List<HardwareActionDict> actionDicts = entry.getValue();
            for (HardwareActionDict actionDict : actionDicts) {
                String[] paramNameAfter = actionDict.getParamLists().split(",");
                StringBuilder paramIds = new StringBuilder();
                for (String s : paramNameAfter) {
                    HardwareActionParamDict paramDict = new HardwareActionParamDict();
                    paramDict.setActionId(id);
                    paramDict.setParamName(actionDict.getName() + "_" + s);
                    paramDict.setAddressId(-999);
                    paramDict.setParamId("-999");
                    HardwareActionParamDict savedParamDict = hardwareActionParamDictService.insert(paramDict);
                    if (savedParamDict != null) {
                        HardwareActionMiddle middle = new HardwareActionMiddle();
                        middle.setHardwareId(hardwareDictionaryResult.getId());
                        middle.setParamId(savedParamDict.getId());
                        hardwareActionMiddleService.insert(middle);
                        if (!paramIds.isEmpty()) {
                            paramIds.append(","); // 如果不是第一个元素，则添加逗号
                        }
                        paramIds.append(savedParamDict.getId());
                    }
                }
                ProjectActionDict projectActionDict = new ProjectActionDict();
                projectActionDict.setName(actionDict.getName());
                projectActionDict.setParamIds(paramIds.toString());
                projectActionDict.setHardwareId(hardwareDictionaryResult.getId());
                projectActionDict.setRemarks(actionDict.getRemarks());
                projectActionDictService.insert(projectActionDict);
            }
        }



        //更新推送列表信息
        hardwareCurrentService.initHardwareCurrentAddressMessageMap();


        return hardwareDictionaryResult;
    }

    /**
     * 配置端-删除硬件详情信息
     *
     * @param id 硬件Id
     */
    public void deleteHardwareInfo(Integer id) {
        //删除动作参数中间件
        HardwareActionMiddleQueryCriteria queryCriteria = new HardwareActionMiddleQueryCriteria();
        List<Integer> lists = new ArrayList<>();
        lists.add(id);
        queryCriteria.setHardwareId(lists);
        List<HardwareActionMiddle> hardwareActionMiddleByCondition = hardwareActionMiddleService.findList(queryCriteria);
        //删除动作参数及其中间件
        hardwareActionMiddleByCondition.forEach(hardwareActionMiddle -> {
            hardwareActionMiddleService.deleteById(hardwareActionMiddle.getId());
            hardwareActionParamDictService.deleteById(hardwareActionMiddle.getParamId());
        });
        List<Integer> list = insertList(id);
        ProjectActionDictQueryCriteria queryCriteria1 = new ProjectActionDictQueryCriteria();
        queryCriteria1.setHardwareId(list);
        List<ProjectActionDict> projectActionByCondition = getProjectActionByCondition(queryCriteria1);
        projectActionByCondition.forEach(projectActionDict -> projectActionDictService.deleteById(projectActionDict.getId()));
        //删除硬件信息
        hardwareDictionaryService.deleteById(id);

        //删除硬件abs信息
        hardwareAbsPosServiceImpl.deleteByHardwareId(id);
    }

    /**
     * 配置端-更新硬件相信信息
     *
     * @param request 硬件可修改的地方 以及 补充参数信息
     */
    public void updateHardwareInfo(HardwareInfoConfigReq request) {

        //更新硬件的基本信息
        HardwareDictionary hardwareDictionary = hardwareDictionaryService.selectById(request.getId());

        BeanUtils.copyProperties(request, hardwareDictionary);

        hardwareDictionaryService.update(hardwareDictionary, hardwareDictionary.getId());

        //更新硬件下面的动作
        List<ProjectActionConfigReq> actionParamDicts = request.getActionParamDicts();
        for (ProjectActionConfigReq actionParamDict : actionParamDicts) {
            ProjectActionDict projectActionDict = new ProjectActionDict();
            BeanUtils.copyProperties(actionParamDict, projectActionDict);
            projectActionDictService.update(projectActionDict, projectActionDict.getId());

            List<HardwareInfoActionConfigReq> hardwareInfoActionConfigRespList = actionParamDict.getHardwareInfoActionConfigRespList();
            hardwareInfoActionConfigRespList.forEach(hardwareInfoActionConfig -> {
                HardwareActionParamDict hardwareActionParamDict = new HardwareActionParamDict();
                BeanUtils.copyProperties(hardwareInfoActionConfig, hardwareActionParamDict);
                hardwareActionParamDictService.update(hardwareActionParamDict, hardwareActionParamDict.getId());
            });
        }


        //更新推送列表信息
        hardwareCurrentService.initHardwareCurrentAddressMessageMap();
    }

    /**
     * 配置端-查询所有硬件详情 分页
     *
     * @return /
     */
    public Page<HardwareInfoConfigResp> getHardwareConfigInfoAll(Pageable pageable) {

        //工位字段
        Map<Integer,String> workplaceMap = new HashMap<>();
        List<HardwareWorkplace> workplacesList = hardwareWorkplaceService.selectAll();
        for (HardwareWorkplace hardwareWorkplace : workplacesList) {
            workplaceMap.put(hardwareWorkplace.getId(),hardwareWorkplace.getWorkplaceName());
        }
        //

        List<HardwareInfoConfigResp> returnList = new ArrayList<>();
        Page<HardwareDictionary> allPage = hardwareDictionaryService.findAllPage(new BaseQueryCriteria(), pageable);
        for (HardwareDictionary hardwareDictionary : allPage) {
            HardwareInfoConfigResp hardwareConfigInfoById = getHardwareConfigInfoById(hardwareDictionary.getId());
            //
            hardwareConfigInfoById.setWorkplaceName(workplaceMap.get(hardwareDictionary.getWorkplaceId()));
            hardwareConfigInfoById.setWorkplaceId(hardwareDictionary.getWorkplaceId());
            //
            returnList.add(hardwareConfigInfoById);
        }
        return new PageImpl<>(returnList, pageable, allPage.getTotalElements());
    }

    /**
     * 配置端-查询所有硬件详情
     *
     * @return /
     */
    public List<HardwareInfoConfigResp> getHardwareConfigInfoAll() {
        List<HardwareInfoConfigResp> returnList = new ArrayList<>();
        for (HardwareDictionary hardwareDictionary : hardwareDictionaryService.selectAll()) {
            HardwareInfoConfigResp hardwareConfigInfoById = getHardwareConfigInfoById(hardwareDictionary.getId());
            returnList.add(hardwareConfigInfoById);
        }

        return returnList;
    }

    /**
     * 配置端-查询硬件详情
     *
     * @param id 硬件Id
     * @return /
     */
    public HardwareInfoConfigResp getHardwareConfigInfoById(Integer id) {
        //查询硬件Id
        HardwareDictionary hardwareDictionary = hardwareDictionaryService.selectById(id);
        if (hardwareDictionary != null) {
            //查询硬件详情
            HardwareInfoConfigResp returnResult = new HardwareInfoConfigResp();
            BeanUtils.copyProperties(hardwareDictionary, returnResult);

            //查询类型详情
            Integer hardwareType = hardwareDictionary.getHardwareType();
            HardwareTypeDict hardwareTypeDict = hardwareTypeDictService.selectById(hardwareType);
            if (hardwareTypeDict != null) {
                returnResult.setHardwareTypeDict(hardwareTypeDict);
            }

            //查询地址列表详情
            List<ProjectConfiguration> projectConfigurations = new ArrayList<>();
            String addressArray = hardwareDictionary.getAddressArray();
            List<Integer> ids = stringArrayToIntegerArray(addressArray);

            if (!ids.isEmpty()) {
                List<ProjectConfiguration> batchResult = projectConfigService.findAllByIds(ids);
                projectConfigurations.addAll(batchResult);
                returnResult.setConfigList(projectConfigurations);
            }

            List<ProjectConfiguration> projectConfigurationsShow = new ArrayList<>();
            String showArray = hardwareDictionary.getShowArray();
            if ((showArray != null) && !showArray.isEmpty()) {
                List<Integer> list = stringArrayToIntegerArray(showArray);
                if (!list.isEmpty()) {
                    List<ProjectConfiguration> batchResult = projectConfigService.findAllByIds(list);
                    projectConfigurationsShow.addAll(batchResult);
                    returnResult.setShowViewList(projectConfigurationsShow);
                }
            }

            List<ProjectParameter> projectParameters = new ArrayList<>();
            String paramArray = hardwareDictionary.getParamArray();
            List<Integer> ids1 = stringArrayToIntegerArray(paramArray);
            if (!ids1.isEmpty()) {
                List<ProjectParameter> batchResult = projectParamService.findAllByIds(ids1);
                projectParameters.addAll(batchResult);
                returnResult.setParamList(projectParameters);
            }

            //查询动作参数详情
            List<Integer> hardwareIds = insertList(hardwareDictionary.getId());
            HardwareActionMiddleQueryCriteria queryCriteria = new HardwareActionMiddleQueryCriteria();
            queryCriteria.setHardwareId(hardwareIds);
            List<HardwareActionMiddle> actionMiddles = hardwareActionMiddleService.findList(queryCriteria);
            if (!actionMiddles.isEmpty()) {
                List<HardwareInfoActionConfigResp> actionParamResults = new ArrayList<>();
                actionMiddles.forEach(actionMiddle -> {
                    HardwareActionParamDict hardwareActionParamDict = hardwareActionParamDictService.selectById(actionMiddle.getParamId());
                    if (hardwareActionParamDict != null) {
                        HardwareInfoActionConfigResp actionParamResult = new HardwareInfoActionConfigResp();
                        BeanUtils.copyProperties(hardwareActionParamDict, actionParamResult);
                        //动作不为空，则查出动作
                        HardwareActionDict hardwareActionDict = hardwareActionDictService.selectById(hardwareActionParamDict.getActionId());
                        if (hardwareActionDict != null) {
                            actionParamResult.setActionDict(hardwareActionDict);
                        }
                        //配置不为空，则查出配置
                        ProjectConfiguration projectConfiguration = projectConfigService.selectById(hardwareActionParamDict.getAddressId());
                        if (projectConfiguration != null) {
                            actionParamResult.setProjectConfiguration(projectConfiguration);
                        }

                        //分割查询 参数信息
                        List<ProjectParameter> ProjectParameterList = new ArrayList<>();
                        if (hardwareActionParamDict.getParamId().contains(",")) {
                            String[] paramId = hardwareActionParamDict.getParamId().split(",");
                            for (String s : paramId) {
                                ProjectParameter projectParameter = projectParamService.selectById(Integer.parseInt(s));
                                ProjectParameterList.add(projectParameter);
                            }
                        } else {
                            ProjectParameter projectParameter = projectParamService.selectById(Integer.parseInt(hardwareActionParamDict.getParamId()));
                            ProjectParameterList.add(projectParameter);
                        }
                        if (!ProjectParameterList.isEmpty()) {
                            actionParamResult.setProjectParameter(ProjectParameterList);
                        }
                        actionParamResults.add(actionParamResult);
                    }
                });

                List<ProjectActionConfigResp> actionResult = new ArrayList<>();
                ProjectActionDictQueryCriteria queryCriteria1 = new ProjectActionDictQueryCriteria();
                queryCriteria1.setHardwareId(hardwareIds); // 假设hardwareIds是一个已知且可用的集合
                List<ProjectActionDict> projectActionByCondition = getProjectActionByCondition(queryCriteria1);

                // 使用Java 8的Stream API来简化集合处理
                for (ProjectActionDict projectActionDict : projectActionByCondition) {
                    ProjectActionConfigResp projectActionConfigResp = new ProjectActionConfigResp();
                    BeanUtils.copyProperties(projectActionDict, projectActionConfigResp);

                    // 将paramIds字符串数组转换为整数列表
                    List<Integer> paramIds = stringArrayToIntegerArray(projectActionDict.getParamIds());

                    // 使用Stream API和filter来匹配actionParamResults
                    List<HardwareInfoActionConfigResp> matchedActionParams = actionParamResults.stream().filter(actionParamResult -> paramIds.contains(actionParamResult.getId())).collect(Collectors.toList());

                    // 设置匹配的actionParams到response对象
                    projectActionConfigResp.setHardwareInfoActionConfigRespList(matchedActionParams);

                    // 将处理好的response对象添加到结果列表中
                    actionResult.add(projectActionConfigResp);
                }
                returnResult.setConfigActionList(actionResult);
            }
            return returnResult;
        } else {
            return null;
        }
    }

    public List<HardwareActionDict> backHardwareAction(List<Integer> ids) {
        HardwareActionDictQueryCriteria queryCriteria = new HardwareActionDictQueryCriteria();
        queryCriteria.setId(ids);
        return hardwareActionDictService.findList(queryCriteria);
    }

    public List<Integer> insertList(Integer id) {
        List<Integer> lists = new ArrayList<>();
        lists.add(id);
        return lists;
    }

    //辅助方法: 将字符串转换为 List<Inter>
    public List<Integer> stringArrayToIntegerArray(String stringArray) {
        List<Integer> ids = new ArrayList<>();
        if (stringArray.contains(",")) {
            // 去除空白字符并分割地址，然后尝试转换为整数
            ids = Arrays.stream(stringArray.split(",")).map(String::trim).filter(s -> !s.isEmpty()) // 排除空字符串
                    .map(this::tryParseInt) // 尝试将字符串转换为整数，忽略无效的
                    .filter(Objects::nonNull) // 排除转换失败的null值
                    .collect(Collectors.toList());
        } else {
            if(!(stringArray.isEmpty()||stringArray.equals("")||stringArray==null)){

                int i = Integer.parseInt(stringArray);
                ids.add(i);

            }

//            int i = Integer.parseInt(stringArray);
//            ids.add(i);
        }
        return ids;
    }

    // 辅助方法：尝试将字符串转换为整数，如果失败则返回null
    private Integer tryParseInt(String s) {
        try {
            return Integer.parseInt(s);
        } catch (NumberFormatException e) {
            // 可以选择记录日志或忽略，这里选择忽略
            return null;
        }
    }

    /**
     * 初始化项目的配置信息
     */
    public List<ProjectConfiguration> initProjectConfiguration(String projectName) {
        //查询项目下的所有配置信息
        ProjectConfigQueryCriteria queryCriteria = new ProjectConfigQueryCriteria();
        queryCriteria.setProject(projectName);
        return projectConfigService.findList(queryCriteria);
    }


    /**
     * 配置端-查询所有硬件工位详情 分页
     *
     * @return /
     */
    public Page<HardwareWorkplace> getHardwareWorkplaceAll(Pageable pageable) {
        List<HardwareWorkplace> returnList = new ArrayList<>();
        Page<HardwareWorkplace> allPage = hardwareWorkplaceService.findAllPage(new BaseQueryCriteria(), pageable);
        for (HardwareWorkplace hardwareWorkplace : allPage) {
            HardwareWorkplace hardwareConfigInfoById = hardwareWorkplaceService.selectById(hardwareWorkplace.getId());
            returnList.add(hardwareConfigInfoById);
        }
        return new PageImpl<>(returnList, pageable, allPage.getTotalElements());
    }


    /**
     * 获取实时数据推送对象
     *
     * @return
     */


    public HardwareCurrentMessageResp getCurrentMessage(){
        HardwareCurrentMessageResp hardwareCurrentMessageResp = new HardwareCurrentMessageResp();

        hardwareCurrentMessageResp.setHardwareCurrentMsg(HardwareCurrentService.HardwareCurrentAddressMap);
        hardwareCurrentMessageResp.setIoCurrentMsg(HardwareCurrentService.HardwareConfigCurrentMsg);
        List<Integer> productions = new ArrayList<>();
        productions.add(ProductionService.dayProduction);
        productions.add(ProductionService.allProduction);
        hardwareCurrentMessageResp.setProductions(productions);

        return hardwareCurrentMessageResp;
    }


    /**
     * 获取实时数据推送对象
     *
     * @return
     */
    public List<ProjectConfiguration>  getHardwareConfig(){
        return ProjectConfigProcessService.projectConfigurations;
    }



    /**
     * 内存项目配置，查询
     *
     * @param queryCriteria 查询条件
     * @param pageable      分页条件
     * @return /
     */
    public Page<ProjectConfiguration> getProjectConfigRamByCondition(ProjectConfigQueryCriteria queryCriteria, Pageable pageable) {
        //获取内存
        List<ProjectConfiguration> Ram = new ArrayList<>();
        for (ProjectConfiguration projectConfiguration :  ProjectConfigProcessService.projectConfigurations) {
            if((queryCriteria.getAddress()==""||queryCriteria.getAddress().equals(projectConfiguration.getAddress()))&&(queryCriteria.getDbAddress()==""||queryCriteria.getDbAddress().equals(projectConfiguration.getDbAddress()))&&(queryCriteria.getProject()==""||queryCriteria.getProject().equals(projectConfiguration.getProject()))){
                Ram.add(projectConfiguration);
            }
        }
        List<ProjectConfiguration> tempList = new ArrayList<>();
        //分页查询
        Integer hi = pageable.getPageNumber()*pageable.getPageSize()+pageable.getPageSize();
        if(hi>Ram.size()){
            hi = Ram.size();
        }
        for (int i=pageable.getPageNumber()*pageable.getPageSize();i<hi;i++){
            tempList.add(Ram.get(i));
        }


        Page<ProjectConfiguration> respPage = new PageImpl<>(tempList, pageable, Ram.size());
        return respPage;
    }


    /**
     * 获取硬件信息 By Name
     *
     * @param Name
     * @return
     */
    public HardwareInfoViewResp getHardwareInfoByName(String Name) {
        List<HardwareInfoViewResp> hardwareInfoViewRespList = new ArrayList<>();

        HardwareDictionary hardwareDictionary = hardwareDictionaryService.findHardwareDictionaryByName(Name);

        HardwareInfoViewResp hardwareInfo = getHardwareInfo(hardwareDictionary.getId());
        Map<Integer ,List<ProjectConfiguration>> currentMap = new HashMap<>();
        List<ProjectConfiguration> temp = new ArrayList<>();
        for (ProjectConfiguration projectConfiguration : HardwareCurrentService.HardwareCurrentAddressMessageMap.get(hardwareDictionary.getId())) {
            temp.add(projectConfiguration);
        }
        currentMap.put(hardwareDictionary.getId() , temp);
        hardwareInfo.setHardwareCurrentMsg(currentMap);

        //获取硬件下Abs信息
        List<HardwareAbsPosResp> hardwareAbsPosList = new ArrayList<>();
        for (HardwareAbsPos hardwareAbsPos : hardwareAbsPosServiceImpl.findByHardwareId(hardwareDictionary.getId())) {
            HardwareAbsPosResp hardwareAbsPosResp = new HardwareAbsPosResp();
            BeanUtils.copyProperties(hardwareAbsPos,hardwareAbsPosResp);
            hardwareAbsPosList.add(hardwareAbsPosResp);
        }
        hardwareInfo.setAbsPosList(hardwareAbsPosList);

        return hardwareInfo;
    }


    /**
     * 修改Plc中Configuration的值
     *
     * @param configId
     * @param value
     */
    public void SendCmdPlcByConfigId(Integer configId,String value){
        ProjectConfiguration configuration = getProjectConfigById(configId);
        configuration.setValue(value);
        controlHardwareSendByProtocol(configuration , CommonParmaOpt.s7 ,"");


    }


    /**
     * 修改 HomePos 的值
     *
     * @param req
     */
    public void saveHomePos(ControlCmdSetReq req) {
        //查询硬件详情
        HardwareInfoViewResp hardwareInfo = getHardwareInfo(req.getHardwareId());
        String portD;
        String hardwareProtocol = hardwareInfo.getHardware_protocol();

        //获取需要写入的端口号
        String type = hardwareInfo.getHardware_protocol_view().getType();
        if (type.equals("com")) {
            if (hardwareInfo.getHardware_protocol_view().getPortComm() != null) {
                portD = hardwareInfo.getHardware_protocol_view().getPortComm().getPort();
                log.info("写入的COMIP地址:{},,,{}", portD, hardwareProtocol);
            } else {
                portD = "";
            }
        } else {
            if (hardwareInfo.getHardware_protocol_view().getPortSocket() != null) {
                String clientIp = hardwareInfo.getHardware_protocol_view().getPortSocket().getServerIp();
                String clientPort = hardwareInfo.getHardware_protocol_view().getPortSocket().getServerPort();
                portD = clientIp + ":" + clientPort;
                log.info("写入的TCPIP地址:{},,,{}", portD, hardwareProtocol);
            } else {
                portD = "";
            }
        }

        //获取硬件下的所有动作
        hardwareInfo.getConfigActionList().forEach(configAction -> {
            //指定动作
            if (Objects.equals(configAction.getId(), req.getActionId())) {
                //获取动作下的参数
                List<HardwareInfoActionConfigResp> hardwareInfoActionConfigRespList =
                        configAction.getHardwareInfoActionConfigRespList();
                //如果参数相等，则设置
//                Float magnification = hardwareInfo.getMagnification();

//                for (int i = 0; i < hardwareInfoActionConfigRespList.size(); i++) {
//                    HardwareInfoActionConfigResp hardwareInfoActionConfigResp = hardwareInfoActionConfigRespList.get(i);
//                    if(hardwareInfoActionConfigResp.getProjectConfiguration().getValueType()==3){
//                        float v = Float.parseFloat(req.getActionParam().get(i).getParamValue()) * magnification;
//                        req.getActionParam().get(i).setParamValue(String.valueOf(v));
//                    }
//                    hardwareInfoActionConfigResp.getProjectConfiguration().setValue(req.getActionParam().get(i).getParamValue());
//                    log.info("{}",hardwareInfoActionConfigResp.getProjectConfiguration());
//
//                    controlHardwareSendByProtocol(hardwareInfoActionConfigResp.getProjectConfiguration(), hardwareProtocol, portD);
//
//                }
                //获取currPos中的值
                ProjectConfiguration hardwareConfig = hardwareInfoActionConfigRespList.get(1).getProjectConfiguration();
                String value = hardwareCurrentService.getProjectConfiguration(ProjectConfigProcessService.projectConfigurations , hardwareConfig).getValue();

                //向HomePos写入value
                HardwareInfoActionConfigResp hardwareInfoActionConfigResp = hardwareInfoActionConfigRespList.get(0);
                hardwareInfoActionConfigResp.getProjectConfiguration().setValue(value);
                log.info("{}",hardwareInfoActionConfigResp.getProjectConfiguration());
                controlHardwareSendByProtocol(hardwareInfoActionConfigResp.getProjectConfiguration(), hardwareProtocol, portD);
            }
        });
    }




    public List<HardwareInfoViewResp> getHardwareInfoByhardwareType(Integer hardwareType) {
        List<HardwareInfoViewResp> hardwareInfoViewRespList = new ArrayList<>();
        List<HardwareDictionary> hardwareDict = hardwareDictionaryService.HardwareInfoByworkplaceId(hardwareType);
        for (HardwareDictionary hardwareDictionary : hardwareDict) {
            HardwareInfoViewResp hardwareInfo = getHardwareInfo(hardwareDictionary.getId());
            Map<Integer ,List<ProjectConfiguration>> currentMap = new HashMap<>();
            List<ProjectConfiguration> temp = new ArrayList<>();
            for (ProjectConfiguration projectConfiguration : HardwareCurrentService.HardwareCurrentAddressMessageMap.get(hardwareDictionary.getId())) {

                temp.add(projectConfiguration);

            }
            currentMap.put(hardwareDictionary.getId() , temp);
            hardwareInfo.setHardwareCurrentMsg(currentMap);

            //获取硬件下Abs信息
            List<HardwareAbsPosResp> hardwareAbsPosList = new ArrayList<>();
            for (HardwareAbsPos hardwareAbsPos : hardwareAbsPosServiceImpl.findByHardwareId(hardwareDictionary.getId())) {
                HardwareAbsPosResp hardwareAbsPosResp = new HardwareAbsPosResp();
                BeanUtils.copyProperties(hardwareAbsPos,hardwareAbsPosResp);
                hardwareAbsPosList.add(hardwareAbsPosResp);
            }
            hardwareInfo.setAbsPosList(hardwareAbsPosList);


            hardwareInfoViewRespList.add(hardwareInfo);
        }
        return hardwareInfoViewRespList;
    }


//    public Map<String,String> getsystemList(){
//        List<HardwareInfoViewResp> hardwareInfoViewRespList = new ArrayList<>();
//        HardwareDictionary hardwareDictionary = hardwareDictionaryService.findHardwareDictionaryByName("系统设置");
//        HardwareInfoViewResp hardwareInfo = getHardwareInfo(hardwareDictionary.getId());
//
//        List<String> paramNameList = new ArrayList<>();
//        Map<String,String> systemParamList = new HashMap<>();
//
//        for (ProjectActionConfigResp projectActionConfigResp : hardwareInfo.getConfigActionList()) {
//            systemParamList.put()
//
//            paramNameList.add(projectActionConfigResp.getHardwareInfoActionConfigRespList().get(0).getProjectConfiguration().getRemarks());
//        }
//
//        hardwareInfo.setParamNameList(paramNameList);
//
//        hardwareInfoViewRespList.add(hardwareInfo);
//
//        return null;
//    }



}